package com.healthcare.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.healthcare.client.mapper.GroupMapper;
import com.healthcare.client.mapper.ReferralMapper;
import com.healthcare.client.mapper.UserMapper;
import com.healthcare.client.pojo.Group;
import com.healthcare.client.pojo.Message;
import com.healthcare.client.mapper.MessageMapper;
import com.healthcare.client.pojo.Referral;
import com.healthcare.client.pojo.User;
import com.healthcare.client.service.MessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.healthcare.client.service.UserService;
import com.healthcare.client.utils.ApplicationContextUtil;
import com.healthcare.client.vo.MessageVo;
import com.healthcare.client.vo.MsgVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 聊天记录 服务实现类
 * </p>
 *
 * @author 新华医院转诊联盟
 * @since 2020-04-13
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    @Autowired
    private UserService userService;

    @Autowired
    private ReferralMapper referralMapper;
    @Autowired
    private GroupMapper groupMapper;

    /**
     * 房间号 -> 组成员信息
     */
    private static ConcurrentHashMap<String, List<Session>> groupMemberInfoMap = new ConcurrentHashMap<>();
    /**
     * 房间号 -> 在线人数
     */
    private static ConcurrentHashMap<String, Set<Integer>> onlineUserMap = new ConcurrentHashMap<>();

    /**
     *  获取连接的用户信息
     * @param sid
     * @param userId
     * @param onlineSum
     */
    public void sendInfo(String sid, Integer userId, Integer onlineSum) {
        // 获取该连接用户信息
        User currentUser =   ApplicationContextUtil.getApplicationContext().getBean(UserMapper.class).selectById(userId);
        // 发送通知
//        List<MsgVo> msg = new ArrayList<>();
        MsgVo msgVo = new MsgVo();
        msgVo.setCount(onlineSum);
        msgVo.setAvatar(currentUser.getAvatar());
        // json对象转字符串
//        if (se==0){
//            msgVo.setUserId(0);
//             msgVo.setMsg("这里是分诊台为你服务");
////             msgVo.setUserId(userId);
//            String text = JSONObject.toJSONString(msgVo);
//            onMessage(sid, userId, text);
//        }

    }

    /**
     * 发送消息
     * @param sid
     * @param userId
     * @param message
     */
    @Override
    public void onMessage(String sid, Integer userId, String message) {
        User user= userService.userAdmin();  // 表示小助手信息
        List<Session> sessionList = groupMemberInfoMap.get(sid);
        Set<Integer> onlineUserList = onlineUserMap.get(sid);
        MsgVo msg = JSONObject.parseObject(message, MsgVo.class);
        //判断登录第一次不进  发送消息才进
        if (!StringUtils.isEmpty(msg.getCaseY())){

            Message message1  = new Message();
            //添加至消息记录表
            //会诊转诊判断
            if (msg.getType()==0){  // 代表会诊
                message1.setGroupConsultationId(msg.getId());
            }

            if (msg.getType()==1){  //代表转诊
                message1.setReferralId(msg.getId());
            }

            //判断是医生发送的消息 还是小助手
            if (msg.getCaseY()==0){   //等于0是医生
                message1.setContent(msg.getMsg()); //消息内容
                message1.setDoctor(msg.getUserId());   //医生id
                message1.setLittleHelperId(user.getId());  //小助手ID
                message1.setIsDoct(1);  //是否为医生一表示是
                message1.setHaveRead(0); //是否已读 0表示未读
            }

            //判断是医生发送的消息 还是小助手
            if (msg.getCaseY()==1){   //等于1是小助手
                message1.setContent(msg.getMsg()); //消息内容

                //通过会诊或者转诊ID 查询医生ID
                if (msg.getType()==0){  // 代表会诊
                    Group group =  groupMapper.selectById(msg.getId());
                    message1.setDoctor(group.getDoctorId());   //医生id
                }

                if (msg.getType()==1){  //代表转诊
                    Referral referral= referralMapper.selectById(msg.getId());
                    message1.setDoctor(referral.getDoctorId());   //医生id
                }

                message1.setLittleHelperId(user.getId());  //小助手ID
                message1.setIsDoct(0);  //是否为医生 表示不是
                message1.setHaveRead(0); //是否已读 0表示未读
            }


            // 添加信息至消息表
            baseMapper.insert(message1);


        }
        // 先一个群组内的成员发送消息
        for (Session item : sessionList) {
            try {
                // json字符串转对象
                msg.setCount(onlineUserList.size());
                // json对象转字符串
                String text = JSONObject.toJSONString(msg);

                //传给前台数据
                item.getBasicRemote().sendText(text);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 建立连接调用的方法，群成员加入
     *
     * @param session
     * @param sid
     */
    @Override
    public void onOpen(Session session, String sid, Integer userId) {
        List<Session> sessionList = groupMemberInfoMap.computeIfAbsent(sid, k -> new ArrayList<>());
        Set<Integer> onlineUserList = onlineUserMap.computeIfAbsent(sid, k -> new HashSet<>());
        onlineUserList.add(userId);
        sessionList.add(session);
        // 发送上线通知
        sendInfo(sid, userId, onlineUserList.size());
    }


    /**
     * 关闭连接调用的方法，群成员退出
     *
     * @param session
     * @param sid
     */
    @Override
    public void onClose(Session session, String sid, Integer userId) {
        List<Session> sessionList = groupMemberInfoMap.get(sid);
        sessionList.remove(session);
        Set<Integer> onlineUserList = onlineUserMap.get(sid);
        onlineUserList.remove(userId);
        // 发送离线通知
//        sendInfo(sid, userId, onlineUserList.size(), 0);
    }


    /**
     * 显示消息记录
     * @param type  区分是转诊还是会诊
     * @param userId  // 医生ID或者小助手
     * @return
     */
    @Override
    public List<MessageVo> messageLsit(Integer caseId, Integer type, Integer userId) {
         User user=  userService.userAdmin();  // 获取小助手信息
        Integer groupconsultationid = 0;  //转诊
        Integer referralid = 0;  //会诊
        if (type==0){  //会诊
            groupconsultationid = caseId;
            if (user.getId()==userId){  //判断前端传过来的用户id等于小助手id 就给值
                Group group =  groupMapper.selectById(caseId);
                userId = group.getDoctorId();
            }
        }
        if (type==1){  //转诊
            referralid = caseId;

            if (user.getId()==userId){  //判断前端传过来的用户id等于小助手id 就给值
                Referral referral= referralMapper.selectById(caseId);
                userId = referral.getDoctorId();
            }
        }
        // 调用消息显示方法
        List<MessageVo> list = baseMapper.messageVo(groupconsultationid,referralid,userId);

        //遍历如果等于小助手 就小助手id付给用户
        for (MessageVo me :list) {
            if (me.getIsdoct()==0){  // 等于小助手
                me.setUserId(me.getHelper());
                me.setUsername(user.getUsername());
                me.setAvatar(user.getAvatar());
            }
        }
        return list;
    }
}
